//
//  WBNetworkManager.swift
//  weibo
//
//  Created by 长城 on 16/12/13.
//  Copyright © 2016年 dhsr. All rights reserved.
//

import UIKit
import AFNetworking

enum WBHTTPMthod{
    case GET
    case POST
}
/// 网络管理工具
class WBNetworkManager: AFHTTPSessionManager {
    
    
    /// 静态区、常量、闭包,在第一次访问时执行闭包，并且将结果保存在shared常量中
    static let shared = WBNetworkManager()
    /// 访问令牌，所有网络请求都基于此令牌（登录除外）
    var accessToken : String? = "2.00g8fudG0lfLFi1ebc4db2de0LbgzE"
    let uid = "6086579784"
    /// 专门负责拼接 token 的网络请求方法
    func tokenRequest(method:WBHTTPMthod = .GET,URLString : String,params: [String: AnyObject]?,completion:@escaping (_ json:AnyObject?,_ isSuccess:Bool)->()){
        
        guard let token = accessToken else {
            //FIXME:-发送通知，提示用户登录 
            print("没有token，需要登录")
            completion(nil,false)
            
            return
        }
        
        var parameters = params
        if parameters == nil {
            parameters = [String:AnyObject]()
        }
        
        parameters!["access_token"] = token as AnyObject?
        //调用request方法
        request(URLString: URLString, params: parameters!, completion: completion)
    }
    /// 封闭AFN的GET/POST请求
    ///
    /// - Parameters:
    ///   - method: GET/POST
    ///   - URLString: URLString
    ///   - params: 参数字典
    ///   - completion: 完成回调(json(字典\数组),是否成功)
    func request(method:WBHTTPMthod = .GET,URLString : String,params: [String: AnyObject],completion:@escaping (_ json:AnyObject?,_ isSuccess:Bool)->()){
        let success = { (task : URLSessionDataTask,json : Any?) ->() in
                completion(json as AnyObject?,true)
        }
        let failure = {(task:URLSessionDataTask?,error : Error)->() in
            
                print("网络请求错误\(error)")
                //针对403错误处理token过期
            if (task?.response as? HTTPURLResponse)?.statusCode == 403{
                print("token过期了")
                
                //FIXME:-发送通知（本方法不知道补充谁调用，谁接收到谁处理）
            }
                completion(nil,false)
        }
        if method == .GET {
            get(URLString, parameters: params, progress: nil, success: success, failure: failure)
        }else{
            post(URLString, parameters: params, progress: nil, success: success, failure: failure)
        }
       
    }
}
extension WBNetworkManager{
    /// 加载微博数据字典数组
    ///
    /// - Parameter completion: 完成回调[list：微博字典数据，是否成功]
    func statusList(since_id : Int64 ,max_id:Int64 , completion : @escaping (_ list: [[String:AnyObject]]?,_ isSuccess: Bool)->()){
        let url = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        let params = ["since_id":"\(since_id)",
        "max_id":"\(max_id)"]
   
        tokenRequest(URLString: url, params: params as [String : AnyObject]?, completion:
            {(json,isSuccess) in
                //print(json ?? "无返回数据")
                let result = json?["statuses"] as? [[String:AnyObject]]
                
                completion(result,true)
        })
    }
    
    /// 返回未读数
    func unreadCount(completion:@escaping (_ count:Int)->()){
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        let params = ["uid":uid]
        
        tokenRequest(URLString: urlString, params: params as [String : AnyObject]?, completion:
            {(json,isSuccess) in
                let dict = json as? [String:AnyObject]
                let count = dict?["status"] as? Int
                completion(count ?? 0)
        })
    }
}
